package com.yc.demo.d0730;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@WebListener
public class OnlineListener implements
        ServletContextListener,      // 应用上下文 生命周期 监听器
        HttpSessionListener,         // 会话      生命周期 监听器
        HttpSessionAttributeListener // 会话      属性编号 监听器
{

    public OnlineListener() {
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("================= contextInitialized =====================");
        // 在上下文初始化时, 创建一个在线人数集合 map<用户名, 上线的时间>
        Map<String,Long> onlineMap = new LinkedHashMap<>();
        // 获取上下文对象
        final ServletContext servletContext = sce.getServletContext();
        // 将在线人数集合存入上下文
        servletContext.setAttribute("onlineMap", onlineMap);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("================= contextInitialized =====================");
    }

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        System.out.println("================= sessionCreated =====================");
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("================= sessionDestroyed =====================");
    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent sbe) {
        System.out.println("================= attributeAdded =====================");
        if("loginedUser".equals(sbe.getName())){
            final ServletContext servletContext = sbe.getSession().getServletContext();
            Map<String,Long> onlineMap = (Map<String, Long>) servletContext.getAttribute("onlineMap");
            // 将上线人姓名 + 当前时间, 保存到集合中
            onlineMap.put((String) sbe.getValue(), System.currentTimeMillis());
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent sbe) {
        System.out.println("================= attributeRemoved =====================");
        if("loginedUser".equals(sbe.getName())){
            final ServletContext servletContext = sbe.getSession().getServletContext();
            Map<String,Long> onlineMap = (Map<String, Long>) servletContext.getAttribute("onlineMap");
            // 将上线人姓名 + 当前时间, 保存到集合中
            onlineMap.remove((String) sbe.getValue());
        }
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent sbe) {
        System.out.println("================= attributeReplaced =====================");
    }
}
